package com.knowledge.plus.java8;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Stream 串行流
 * parallelStream 并行流
 * https://blog.csdn.net/qq_45735918/article/details/119325371
 *
 * @author TPF
 * @since 2022/12/16
 */
public class StreamAndParallelStream {

    /**
     * stream() + 线程不安全的List
     */
    @Test
    public void test1() {
        List<Integer> list = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            list.add(i);
        }
        List<Integer> testList = new ArrayList<>();
        long startTime = System.currentTimeMillis();   //获取开始时间
        list.stream().forEach(l -> {
            try {
                Thread.sleep(100);
                testList.add(l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("程序运行时间： " + (endTime - startTime) + "ms");
        System.out.println("集合大小：" + testList.size());
    }

    /**
     * parallelStream()并行流 + 线程不安全的List
     */
    @Test
    public void test2() {
        List<Integer> list = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            list.add(i);
        }
        List<Integer> testList = new ArrayList<>();
        long startTime = System.currentTimeMillis();   //获取开始时间
        list.parallelStream().forEach(l -> {
            try {
                Thread.sleep(100);
                testList.add(l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("程序运行时间： " + (endTime - startTime) + "ms");
        System.out.println("集合大小：" + testList.size());
    }

    /**
     * parallelStream()并行流 + 线程安全的List
     */
    @Test
    public void test3() {
        List<Integer> list = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            list.add(i);
        }
        List<Integer> testList = Collections.synchronizedList(new ArrayList<>());
        long startTime = System.currentTimeMillis();   //获取开始时间
        list.parallelStream().forEach(l -> {
            try {
                Thread.sleep(100);
                testList.add(l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("程序运行时间： " + (endTime - startTime) + "ms");
        System.out.println("集合大小：" + testList.size());
    }

}
